class QLibCrypto {
    constructor (url) {
        this.serUrl = ''
        if(url){
            this.url = url
        }else{
            this.url = 'wss://127.0.0.1:39443/'
        }
        this.ws = null; // 判断当前浏览器是否支持WebSocket
        this.lockReconnect = false; //避免ws重复连接
        this.deviceObj = {
            deviceId: '',
            peerId: '',
            peerQccsId: '',
            systemId: '',
            keyId: ''
        };
        this.encryptTxtFromServer = {
            cipherData:""
        }
        this.originTxtFromServer = ''
        this.deviceArray = []
        this.initParams ={}
        this.deceNum = 0
        this.setPath=''
        this.suffix='png,jpg,jpeg,gif,pdf,bmp,doc,docx,xls,xlsx,txt'
        this.dirId = 'a'
        this.dirIdNum = '0'
        this.currentDirObj={}
        this.maxFileSize=20
        this.maxLinkNum=0
        this.filterFolder = true
        this.isShowllwjj = true
        this.userKey = {
          puk:'',
          signData:'',
        }
        this.prams={}
    }
    hexToArray ( str ) {
        const arr = []
        for (let i = 0, len = str.length; i < len; i += 2) {arr.push (parseInt (str.substr (i, 2), 16))}
        return new Uint8Array (arr)
    }
    ArrayToHex ( arr ) {
        let hex = ''
        arr.map (item => {
            item = item.toString (16)
            hex += item.length === 1 ? '0' + item : item
        })
        return hex
    }
    utf8ToArray ( str ) {
        const arr = []
        for (let i = 0, len = str.length; i < len; i++) {
            const point = str.codePointAt (i)
            if (point <= 0x007f) {arr.push (point)} else if (point <= 0x07ff) {
                arr.push (0xc0 | ( point >>> 6 ))
                arr.push (0x80 | ( point & 0x3f ))
            } else if (point <= 0xd7ff || ( point >= 0xe000 && point <= 0xffff )) {
                arr.push (0xe0 | ( point >>> 12 ))
                arr.push (0x80 | ( ( point >>> 6 ) & 0x3f ))
                arr.push (0x80 | ( point & 0x3f ))
            } else if (point >= 0x010000 && point <= 0x10ffff) {
                i++
                arr.push (0xf0 | ( ( point >>> 18 ) & 0x1c ))
                arr.push (0x80 | ( ( point >>> 12 ) & 0x3f ))
                arr.push (0x80 | ( ( point >>> 6 ) & 0x3f ))
                arr.push (0x80 | ( point & 0x3f ))
            } else {
                arr.push (point)
                throw new Error ('input is not supported')
            }
        }
        return new Uint8Array (arr)
    }
    arrayToUtf8 ( arr ) {
        const str = []
        for (let i = 0, len = arr.length; i < len; i++) {
            if (arr[ i ] >= 0xf0 && arr[ i ] <= 0xf7) {
                str.push (String.fromCodePoint (( ( arr[ i ] & 0x07 ) << 18 ) + ( ( arr[ i + 1 ] & 0x3f ) << 12 ) + ( ( arr[ i + 2 ] & 0x3f ) << 6 ) + ( arr[ i + 3 ] & 0x3f )))
                i += 3
            } else if (arr[ i ] >= 0xe0 && arr[ i ] <= 0xef) {
                str.push (String.fromCodePoint (( ( arr[ i ] & 0x0f ) << 12 ) + ( ( arr[ i + 1 ] & 0x3f ) << 6 ) + ( arr[ i + 2 ] & 0x3f )))
                i += 2
            } else if (arr[ i ] >= 0xc0 && arr[ i ] <= 0xdf) {
                str.push (String.fromCodePoint (( ( arr[ i ] & 0x1f ) << 6 ) + ( arr[ i + 1 ] & 0x3f )))
                i++
            } else {str.push (String.fromCodePoint (arr[ i ]))}
        }
        return str.join ('')
    }
    emptyData ( val ) {
        if (!val || Object.prototype.toString.call (val) !== '[object String]') {
            return val
        }
        var newVal = ''
        newVal = val.replace (/\s*/g, '')
        return newVal
    }
    initEventHandle (callback ) {
        let _this = this
        // 此callBack为其他地方调用时定义的接收webSocket数据接收的函数
        if (callback) {
            if (typeof callback === 'function') {
                _this.globalCallback = callback
            } else {
                //throw new Error ('callBack is not a function')
            }
        }
        this.maxLinkNum ++
        var obj = {
            code: 0,
            data: {},
            optWeb: 8,// web的操作1提示需要进行获取初始化数据,web的操作2提示需要进行PIN码操作，
            // 3web隐藏PIN吗数据提示，4web端显示解密结果，5显示密文同时web端进行解密，8和server协商使用密钥句柄
            //3创建密钥协商参数， 4web端显示解密结果，5显示密文同时web端进行解密，6web端隐藏PIN吗数据提示 7和服务端SDK协商使用密钥句柄
            message: '',
        }
        try {
            if ('WebSocket' in window) {
                _this.ws = new WebSocket (_this.url)
                _this.ws.onclose = function () {
                    _this.reconnect (_this.url)
                    obj.code = 1
                    obj.optWeb = 8
                    obj.message = 'WebSocket连接关闭!' + new Date ().toLocaleString ()
                    _this.globalCallback (obj)
                }
                _this.ws.onerror = function () {
                    _this.reconnect (_this.url)
                    obj.code = 1
                    obj.optWeb = 8
                    obj.message = 'WebSocket连接错误!' + new Date ().toLocaleString ()
                    _this.globalCallback (obj)
                }
                _this.ws.onopen = function () {
                    //_this.getDeviceInfo ()
                    obj.code = 0
                    obj.optWeb = 9
                    //obj.message = 'WebSocket连接成功!' + new Date ().toLocaleString ()
                    _this.globalCallback (obj)
                }
                _this.ws.onmessage = function ( event ) {
                    try {
                        var res = JSON.parse (event.data)
                        obj.data = {
                            deviceId: '',  //设备ID
                            initFlag: 0,   //ukey初始化标识1初始化，0未初始
                            pin_need_verify: 1//1需要校验PIN，0不需要校验PIN
                        }
                        if (res.ret === 0) {
                            obj.code = 0
                            _this.originTxtFromServer = ''
                            obj.message = ''
                            if (res.opt === 1) {
                                _this.deviceArray = res.data
                                obj.optWeb = 1
                                _this.deviceObj = res.data[0]
                                obj.data = _this.deviceArray
                                _this.globalCallback(obj)
                            } else if (res.opt === 2) {
                                obj.optWeb = 8
                                obj.data = _this.deviceObj
                                _this.globalCallback (obj)
                            } else if (res.opt === 3) {
                                obj.message = '加密请求成功'
                                obj.optWeb = 5
                                obj.data = res.data
                                _this.globalCallback (obj)
                            } else if (res.opt === 4) {
                                obj.message = '解密请求成功'
                                obj.optWeb = 4
                                obj.data = ''
                                if(res.data !== undefined && res.data.plain_text !== undefined){
                                    obj.data = _this.arrayToUtf8(_this.hexToArray(res.data.plain_text))
                                }
                                _this.globalCallback (obj)
                            } else if (res.opt === 5) {
                                sessionStorage.removeItem('QLibCryptoKeyId')
                            } else if (res.opt === 6) {
                                obj.message = '校验密码成功'
                                obj.optWeb = 6
                                obj.data = ''
                                _this.globalCallback (obj)
                            } else if (res.opt === 7) {
                                obj.message = ''
                                obj.optWeb = 7
                                /*console.log(_this.prams)
                                _this.oriFun()*/
                                _this.globalCallback (obj)
                            }else if (res.opt === 8) {
                                obj.optWeb = 81
                                obj.data = res.data
                                _this.globalCallback (obj)
                            }else if (res.opt === 9) {
                                obj.optWeb = 91
                                obj.data = res.data
                                _this.globalCallback (obj)
                            }else if (res.opt === 10) {
                                obj.optWeb = 101
                                _this.globalCallback (obj)
                                _this.getDeviceInfo()
                            }else if (res.opt === 11) {
                                obj.optWeb = 111
                                obj.message = '删除内存PIN码成功'
                                _this.globalCallback (obj)
                            }else if (res.opt === 12) {
                                let newData = res.data
                                let newObj = {
                                    code:0,
                                    optWeb:112,
                                    message:'',
                                }
                                for(var m=0; m< newData.FileList.length; m++){
                                    var item = newData.FileList[m]
                                    if(_this.setPath === ''){
                                        item.value = newData.EnumPath+item.fileName
                                    }else{
                                        item.value = newData.EnumPath+'\\'+item.fileName
                                    }
                                    item.parentPath = newData.EnumPath
                                    item.id = _this.dirId+m+_this.dirIdNum
                                    _this.dirIdNum ++
                                }
                                newObj.data = newData.FileList
                                if(_this.isShowllwjj){
                                    _this.bodyInsertllwjj(newObj.data)
                                }else{
                                   _this.sonClickList(_this.currentDirObj,newObj.data)
                                }
                            }else if (res.opt === 13) {
                              obj.message = '获取公钥成功'
                              obj.optWeb = 113
                              obj.data = ''
                              if(res.data !== undefined && res.data.puk !== undefined){
                                obj.data = res.data.puk
                                _this.userKey.puk =res.data.puk
                              }
                              _this.globalCallback (obj)
                            }else if (res.opt === 14) {
                              obj.message = '获取签名成功'
                              obj.optWeb = 114
                              obj.data = ''
                              if(res.data !== undefined && res.data.sign_data !== undefined){
                                obj.data = res.data.sign_data
                                _this.userKey.signData =res.data.sign_data
                              }
                              _this.globalCallback (obj)
                            }else if (res.opt === 15) {
                              obj.message = '修改PIN码成功'
                              obj.optWeb = 115
                              obj.data = ''
                              _this.globalCallback (obj)
                            }
                        } else {
                            if (res.opt === 5) {
                                return
                            }
                            if (res.opt === 10) {
                                obj.optWeb = 2
                                _this.globalCallback (obj)
                                return
                            }
                            obj.code = 1
                            var a = parseInt (res.ret)
                            obj.optWeb = a
                            if (a === 4097) {
                                obj.code = 0
                                obj.optWeb = 2
                                if(res.data !== undefined){
                                    obj.message = 'PIN不对，还剩下'+res.data.retry_times+'次数，请重新输入'
                                }else{
                                    obj.message = '请输入PIN码'
                                }
                            } else if (a === 4098) {
                                obj.message = '请插入UKEY'
                            } else if (a === 4099) {
                                obj.code = 0
                                obj.optWeb = 2
                                obj.message = 'UKEY登录失败'
                                _this.deviceObj.keyId = ''
                            } else if (a === 4100) {
                                obj.message = 'UKEY初始化资源失败！'
                            } else if (a === 4101) {
                                obj.message = '算法ID不存在（目前支持SMS4_ECB/SMS4_CBC/SMS4_CFB/SMS4_OFB)！'
                            } else if (a === 4102) {
                                obj.message = '密钥句柄不存在！'
                            } else if (a === 4103) {
                                obj.message = '内存不足'
                            } else if (a === 4104) {
                                obj.message = '密钥句柄生成失败'
                            } else if (a === 4105) {
                                obj.message = '加密失败'
                            } else if (a === 4106) {
                                obj.message = '解密失败'
                            } else if (a === 4107) {
                                obj.message = 'opcode不存在'
                            } else if (a === 4108) {
                                obj.message = 'Json格式错误'
                            } else if (a === 4109) {
                              obj.message = '当前UKEY不存在此systemID的系统'
                            } else if (a === 4111) {
                                obj.message = 'UKEY已锁定，请联系管理员该UKEY进行解锁'
                            }else if (a === 4112) {
                                obj.message = 'MAC检验失败'
                            }else if (a === 4113) {
                                obj.message = '保存自动登录Pin失败'
                            }else if (a === 4114) {
                                obj.message = '无自动登录Pin'
                            }else if (a === 4115) {
                                obj.message = '删除自动登录pin失败'
                            }else if (a === 4119) {
                              obj.message = '获取公钥失败'
                            }else if (a === 4120) {
                              obj.message = '签名失败'
                            }
                            _this.globalCallback (obj)
                        }
                    } catch (e) {}
                }
            } else {
                alert ('您的浏览器不支持WebSocket。请选择其他的浏览器再尝试连接服务器。')
            }
        } catch (e) {
            _this.reconnect (url)
        }
    }
    reconnect ( url ) {
        if(this.maxLinkNum <= 15){
            let _this = this
            if (_this.lockReconnect) return
            _this.lockReconnect = true
            setTimeout (function () {     //没连接上会一直重连，设置延迟避免请求过多
                _this.initEventHandle (url)
                _this.lockReconnect = false
            }, 2000 * 10)
        }
    }
    globalCallback(e){
        return e
    }
    // 获取qkey的基础信息
    getDeviceInfo () {
        var prams = {
            opt: 1,
            data:{
                need_init_resource:0
            }
        }
        if (this.ws.readyState === 1) {
            // 如果连接正常  给后端发送指定消息
            this.ws.send (JSON.stringify (prams))
        } else {
            // 重连
            this.reconnect ()
        }

    }
    // 首次初始化时，设置qkey初始化参数
    setInitParams ( deviceId) {
        var prams = {
            opt: 7,
            data: {
                'device_id': deviceId,
                'system_id': '000000101',
                'peer_id': 'WT-QSSA_001',
                'qccs_id': 'WT-QCCS100-LOOP'
            }
        }
        this.ws.send (JSON.stringify (prams))
    }
    // 创建密钥通道，生成密钥句柄,协商参数来自于服务端SDK，由业务系统服务端向服务端SDK获取后
    createSecTunnel ( data ) {
        this.deviceObj.keyId = data.keyId
        sessionStorage.setItem('QLibCryptoKeyId',data.keyId)
        let type = 2
        if(data.cipherType === '0'){
            type = 1
        }else if(data.cipherType === '1'){
            type = 0
        }
        var prams = {
            opt: 2,
            data: {
                'device_id': this.deviceObj.deviceId,
                'key_id': this.deviceObj.keyId,
                'check_flag': data.flagChkV,
                'flag': data.flag,
                'enc_flag': type,
                'cipher_qkey': data.ciphreQKey,
                'cipher_qkey_len': 32
            }
        }
        prams.data.flag = JSON.stringify (prams.data.flag)
        this.ws.send (JSON.stringify (prams))
    }
    // 释放AASTU密钥句柄
    freeAgreementQkey () {
        var prams = {
            opt: 5,
            data: {
                key_id: this.deviceObj.keyId
            }
        }
        this.ws.send (JSON.stringify (prams))
    }
    // 校验PIN码
    checkAuthUKey (deviceID, code,isSave ) {
        var prams = {
            opt: 6,
            data: {
                device_id: deviceID,
                pin: code,
                save: 0, // 0不保存，1保存PIN
            }
        }
        //this.prams = prams
        //console.log(this.prams)
        //this.setInitParams(deviceID)
        this.ws.send (JSON.stringify (prams))
    }
   oriFun ( ) {
        this.ws.send (JSON.stringify (this.prams))
    }
    //QCAS加密
    getQkeyEncryptData ( data) {
        this.encryptTxtFromServer = {
            cipherData:""
        }
        var prams = {
            opt: 3,
            data: {
                device_id: this.deviceObj.deviceId,
                key_id: this.deviceObj.keyId,
                alg_id: 'SMS4_CBC',
                encode: 0,
                plain_text: data
            }
        }
        try {
            this.ws.send (JSON.stringify (prams))
        } catch (e) {
            alert('WebSocket连接异常请等待！')
        }
    }
    //QCAS加密
    getQkeyFileEncryptData (path, fileName,type) {
        this.encryptTxtFromServer = {
            cipherData:""
        }
        var prams = {
            opt: 3,
            data: {
                device_id: this.deviceObj.deviceId,
                key_id: this.deviceObj.keyId,
                alg_id: 'SMS4_CBC',
                encode: Number(type),
                plain_text: path+'\\'+fileName
            }
        }
        try {
            this.ws.send (JSON.stringify (prams))
        } catch (e) {
            alert('WebSocket连接异常请等待！')
        }
    }
    //QCAS解密
    getQkeyDecryptData ( data,type,path ) {
        var prams = {
            opt: 4,
            data: {
                iv: data.iv,
                device_id: this.deviceObj.deviceId,
                alg_id: 'SMS4_CBC',
                key_id: this.deviceObj.keyId,
                encode: 2,
                cipher_text: data.cipherData,
                file_path:path
            }
        }
        try {
            this.ws.send (JSON.stringify (prams))
        } catch (e) {
            alert('WebSocket连接异常请等待！')
        }
    }
    //QCAS解密
    getQkeyFileDecryptData ( data,path ) {
        var prams = {
            opt: 4,
            data: {
                iv: data.iv,
                device_id: this.deviceObj.deviceId,
                alg_id: 'SMS4_CBC',
                key_id: this.deviceObj.keyId,
                encode:4,
                cipher_text: data.cipherData,
                file_path:path
            }
        }
        try {
            this.ws.send (JSON.stringify (prams))
        } catch (e) {
            alert('WebSocket连接异常请等待！')
        }
    }
    getCipherParamsData(data){
        var params = {
            "version": "1.0",
            "keyId": sessionStorage.getItem ('QLibCryptoKeyId'),
            "serialIn": "095c27742ed842f2861f83e78bddff2b",
            "algID": "CBC",
            "iv": data.iv,
            "cipherData": data.cipher_text
        }
        return params
    }
    getPlainParamsData(data){
        var params ={
            "version": "1.0",
            "keyId": sessionStorage.getItem('QLibCryptoKeyId'),
            "serialIn": "095c27742ed842f2861f83e78bddff2b",
            "algID": "CBC",
            "iv": "00000000000000000000000000000000",
            "plainData": qs.ArrayToHex(qs.utf8ToArray(data))
        }
        return params
    }
    getServerDecryptData(data){
        return this.arrayToUtf8 (this.hexToArray (data))
    }
    getDoMacData ( data ) {
        var prams = {
            opt: 8,
            data: {
                device_id: this.deviceObj.deviceId,
                key_id: this.deviceObj.keyId,
                encode: 0,
                plain_text: data
            }
        }
        try {
            this.ws.send (JSON.stringify (prams))
        } catch (e) {
            alert('WebSocket连接异常请等待！')
        }
    }
    getVerifyMacParamsData(macObj,data){
        var params =  {
            "version": "1.0",
            "keyId": sessionStorage.getItem('QLibCryptoKeyId'),
            "serialIn":"095c27742ed842f2861f83e78bddff2b",
            "iv": macObj.iv,
            "message": this.ArrayToHex(this.utf8ToArray(data)),
            "mac": macObj.mac
        }
        return params
    }
    getDoMacParamsData(data){
        var params =  {
            "version": "1.0",
            "keyId": sessionStorage.getItem('QLibCryptoKeyId'),
            "serialIn": "c1b434e1a2604be6be1a0184e703745b",
            "iv": "62648bb52baa2a229ff2f5f632ade6e1",
            "message":  this.ArrayToHex(this.utf8ToArray(data))
        }
        return params
    }
    getVerifyMacData ( macObj,data ) {
        var prams = {
            opt: 9,
            data: {
                device_id: this.deviceObj.deviceId,
                key_id: this.deviceObj.keyId,
                encode: 0,
                plain_text: data,
                mac: macObj.mac,
                iv: macObj.iv
            }
        }
        try {
            this.ws.send (JSON.stringify (prams))
        } catch (e) {
            alert('WebSocket连接异常请等待！')
        }
    }
    // 查询是否有有效的PIN
    checkValidPinCode () {
        var prams = {
            opt: 10,
            data: {
                device_id: this.deviceObj.deviceId,
            }        }
        this.ws.send (JSON.stringify (prams))
    }
    // 删除内存PIN码
    deleteAuthUKeyPinCode () {
        var prams = {
            opt: 11,
            data: {
                device_id: this.deviceObj.deviceId,
            }
        }
        this.ws.send (JSON.stringify (prams))
    }
    wsSendPath(path){
        if(path === ''){
            this.setPath = path
        }else{
            this.setPath = path+'\\'
        }
        var prams = {
            opt: 12,
            data: {
                path: path,
                filterFolder:this.filterFolder,
                suffix:this.suffix
            }
        }
        this.ws.send (JSON.stringify (prams))
    }
    findDirPath(isFolder,path,suffix,maxFileSize) {
        if(isFolder !== this.filterFolder){
            this.filterFolder = isFolder
            var showBoxDom = document.getElementById('qs-llwjj')
            if(showBoxDom !== undefined && showBoxDom !== null){
                document.getElementById('qs-llwjj').remove()
                this.dirId = 'a'
                this.dirIdNum = '0'
                this.currentDirObj={}
            }
        }
        if(suffix !== ''&& suffix !== undefined && suffix !== null){
            this.suffix = suffix
        }
        if(maxFileSize !== ''&& maxFileSize !== undefined && maxFileSize !== null){
            this.maxFileSize = maxFileSize
        }
        var suffixArray= this.suffix.split(',')
        if(suffixArray.length > 64){
            alert('最多支持 64个 后缀名过滤数量 ！')
            return
        }
        this.isShowllwjj = true
        if(this.filterFolder && (path+'\\') !== this.setPath){
            var showBoxDom = document.getElementById('qs-llwjj')
            if(showBoxDom !== undefined && showBoxDom !== null){
                document.getElementById('qs-llwjj').remove()
            }
        }
        this.wsSendPath(path,this.filterFolder)
    }
    createMenu(id,dataList) {
        let _this = this
        const menuEl = document.createElement('ul');
        dataList.forEach(item => {
            const itemEl = document.createElement('li');
            const labelEl = document.createElement('span');
            labelEl.id = item.id+'span';
            labelEl.innerText = item.fileName;
            itemEl.appendChild(labelEl);
            itemEl.id = item.id
            if(item.IsDir === 1){
                itemEl.classList.add('icon');
                if(item.IsEmpty === 1){
                    itemEl.classList.add('open');
                }
            }
            labelEl.onclick = function(){
                if(!_this.filterFolder){
                    if(item.IsDir === 1 && item.IsEmpty === 0) {
                        if (itemEl.classList.contains ('open')) {
                            itemEl.classList.remove ('open');
                            if(labelEl.innerText !== itemEl.lastChild.innerText){
                                itemEl.removeChild (itemEl.lastChild)
                            }
                        } else {
                            itemEl.classList.add ('open');
                            _this.wsSendPath (item.value)
                            _this.currentDirObj = item
                        }
                    }
                    if(item.IsDir === 0){
                        _this.currentDirObj = item
                        _this.getLabel(item)
                    }
                }else{
                    if(item.IsDir === 1 && item.IsEmpty === 0) {
                        if (itemEl.classList.contains ('open')) {
                            itemEl.classList.remove ('open');
                            if(labelEl.innerText !== itemEl.lastChild.innerText){
                                itemEl.removeChild (itemEl.lastChild)
                            }
                        } else {
                            itemEl.classList.add ('open');
                            _this.wsSendPath (item.value)
                            _this.currentDirObj = item
                        }
                    }
                    _this.currentDirObj = item
                    _this.getLabel(item)
                }

            }
            menuEl.appendChild(itemEl);
            document.getElementById(id).appendChild(menuEl);
        });
    }
    bodyInsertllwjj(dataList){
      let _this = this
        var showBoxDom = document.getElementById('qs-llwjj')
        if(showBoxDom !== undefined && showBoxDom !== null){
            document.getElementById('qs-llwjj').style.display='inline-block'
        }else{
            const headElement = document.getElementsByTagName('head')[0]
            const styles = this.addStyle()
            headElement.appendChild(styles)
            const div = document.createElement('div');
            var text = ''
            if(this.filterFolder){
                text = '夹'
            }
            var html='<div class="llwjj" id="qs-llwjj">\n' +
              '    <div class="ll-tit">浏览文件'+text+'<a onclick="_this.closellwjj()"></a></div>\n' +
              '    <div class="ll-cont">\n' +
              '        <div class="ll-cont-main" id="menuList"></div>\n' +
              '        <div class="ll-cont-foot">\n' +
              '            <div class="ll-foot-wjm">文件'+text+'名：<input name="wjm" id="fotwjm" readonly/></div>\n' +
              '            <div class="ll-foot-btn"><a onclick="_this.getFileNameAndPath()">确定</a><a onclick="_this.closellwjj()">取消</a></div>\n' +
              '        </div>\n' +
              '    </div>\n' +
              '</div>';
            div.innerHTML = html
            document.body.appendChild(div)
            if(dataList.length >0){
                this.createMenu('menuList',dataList)
            }else{

            }
        }
        this.isShowllwjj = false
    }
    getFileNameAndPath(){
        if(document.getElementById('fotwjm').value === '' && !this.filterFolder){
            alert('请选择以'+this.suffix+'后缀命令的文件！')
            return
        }
        if(document.getElementById('fotwjm').value === '' && this.filterFolder){
            alert('请选择文件夹！')
            return
        }
        if(!this.filterFolder && this.currentDirObj.fileSize > 10 * 1024 * 1024){
            alert('请选择小于10M的文件！')
            return
        }
        let newObj = {
            code:0,
            optWeb:113,
            message:'',
            filterFolder:this.filterFolder,
            data:this.currentDirObj
        }
        if(this.filterFolder){
            this.setPath = this.currentDirObj.value+'\\'
        }else{
            this.setPath = this.currentDirObj.parentPath+'\\'
        }
        this.closellwjj()
        //开始传路劲下发加密命令
        return this.globalCallback (newObj)
    }
    closellwjj(){
        document.getElementById('qs-llwjj').style.display='none'
    }
    getLabel ( item ) {
        if(!this.filterFolder){
            if(item.fileSize >this.maxFileSize*1024*1024){
                alert('请选择小于'+this.maxFileSize+'MB的文件！')
                return
            }
        }
        const list = document.getElementsByClassName('qs-selected');
        for(var i=0; i<list.length; i++){
            list[i].classList.remove ('qs-selected')
        }
        document.getElementById(item.id+'span').classList.add ('qs-selected')
        document.getElementById('fotwjm').value = item.fileName
        this.currentDirObj = item
        /*let fileSelect = document.createElement('input')
        fileSelect.type = 'file'
        fileSelect.style.display = 'none'
        document.body.appendChild(fileSelect)
        fileSelect.click()*/
    }
    sonClickList(item,sonList){
        if(item.IsDir === 1 && this.dirIdNum !==2){
            this.createMenu(item.id,sonList)
        }
    }
    //添加生成文本框的样式
    addStyle() {
        const style = document.createElement('style')
        style.type = 'text/css'
        try {
            style.appendChild(
              document.createTextNode(
                '#qs-llwjj{ position: fixed; width: 420px; height: 500px;left:50%; top:50%; margin-left: -210px; margin-top: -250px; z-index: 9999999;\n' +
                'border: 1px solid #252c33; border-radius: 8px; background: #b8dbfd; color: #000; font-size: 14px;text-align: left;   background: linear-gradient(to bottom,rgba(209,232,254,0.95) 35%,rgba(184,219,253,0.95) 0); overflow: hidden }\n' +
                '#qs-llwjj .ll-tit{width: 100%; height: 30px; line-height: 30px; text-indent: 7px; text-align: left; position: relative;background: linear-gradient(to right,rgba(209,232,254,0.95),rgba(184,219,253,0.99),rgba(209,232,254,0.95)) }\n' +
                '#qs-llwjj .ll-tit a{display:block;width: 47px; height: 19px; line-height: 18px; position: absolute; right: 7px; top: -1px;\n' +
                '    background-size:cover;\n' +
                '    background-image:url("");}\n' +
                '#qs-llwjj .ll-cont{width: 384px; height: 460px;margin: 0 auto; position: relative; background:#f0f0f0;border: 1px solid #5d6c7a;padding: 0 10px; }\n' +
                '#qs-llwjj .ll-cont .ll-cont-top{ width: 100%; height: 30px; line-height: 30px;}\n' +
                '#qs-llwjj .ll-cont .ll-cont-foot{ width: 100%; height: 80px;padding-top:10px; }\n' +
                '#qs-llwjj .ll-cont .ll-cont-foot .ll-foot-wjm{ width: 100%; height: 28px; line-height: 25px; }\n' +
                '#qs-llwjj .ll-cont .ll-cont-foot .ll-foot-wjm input{ width:310px; height: 25px; outline: 0;display:inline-block;background: #fff;\n' +
                '    border-radius: 2px; float: right;  box-sizing: border-box;margin: 0;padding: 0 0 0 5px;\n' +
                '    list-style: none;border: 1px solid #e2e3ea}\n' +
                '#qs-llwjj .ll-cont .ll-cont-foot .ll-foot-wjm input:focus{ outline: 0}\n' +
                '#qs-llwjj .ll-cont .ll-cont-foot .ll-foot-btn{ width: 100%; height: 28px; line-height: 28px;text-align: right;   margin-top: 10px}\n' +
                '#qs-llwjj .ll-cont .ll-cont-foot .ll-foot-btn a{ width:72px; height: 20px; line-height:20px; text-align: center; color: #000;\n' +
                '    margin-left: 10px; border: 1px solid #707070; display: inline-block; border-radius: 4px;\n' +
                '    background: linear-gradient(to bottom,#f0f0f0 50%,rgba(207,207,207,0.6) 0); cursor: pointer}\n' +
                '#qs-llwjj .ll-cont .ll-cont-main{ width:100%; padding-top:5px;height: 362px; overflow-y: auto; overflow-x: hidden;  margin-top: 10px; background: #fff;border: 1px solid #646464; }\n' +
                '#qs-llwjj .ll-cont .ll-cont-main ul{ width:100%;}\n' +
                '#qs-llwjj .ll-cont .ll-cont-main ul li{position: relative;padding-left: 23px;line-height: 30px;list-style: none;width: 100%;cursor: pointer;}\n' +
                '#qs-llwjj .ll-cont .ll-cont-main ul li span{ display: inline-block; padding-left: 20px;padding-right:5px; position: relative; margin-left: -18px; z-index: 2}\n' +
                '#qs-llwjj .ll-cont .ll-cont-main ul .icon::after{\n' +
                '    position: absolute;left: 9px;top: 10px;box-sizing: border-box;width: 12px;height: 12px;line-height: 8px;text-align: center;\n' +
                '    border: 1px solid #AAA;background: #EEE;cursor: pointer;display: block;content: "+";font-size: 12px;font-style: normal;z-index: 0;}\n' +
                '#qs-llwjj .ll-cont .ll-cont-main ul li.open::after{content: "-";}\n' +
                '#qs-llwjj .ll-cont .ll-cont-main .qs-selected{border:1px solid #84acdd; border-radius: 2px; background:linear-gradient(to bottom,rgba(209,232,254,0.05),rgba(184,219,253,0.49)); z-index: 4!important;position: relative;}'
              )
            )
        } catch (ex) {

        }
        return style
    }
    downLoadJson(data,type,fileName){
        var blob = ''
        var name = ''
        if(Number(type) === 1){
            blob =  new Blob([this.decodeToArrayBuffer (data.fileContent)])
            name = data.fileName
        }else if(Number(type) === 2){
            blob = new Blob([qs.hexToArray (data)],{type:"application/octet-binary"})
            name = fileName
        }else if(Number(type) === 3){
            blob = new Blob([data.fileContent],{type:"application/octet-binary"})
            name = data.fileName
        }
        const url =URL.createObjectURL(blob)
        const element = document.createElement('a')
        element.style.display = 'none'
        element.href= url
        const indexDot = name.lastIndexOf('.');
        if(Number(type) === 3){
            element.download = fileName
        }else{
            element.download =name.substring(0,indexDot)+new Date().getTime()+name.substring(indexDot,name.length)
        }
        element.click()
    }
    getTimeFileName(name){
        const indexDot = name.lastIndexOf('.');
        return name.substring(0,indexDot)+new Date().getTime()+name.substring(indexDot,name.length)
    }
    downLoadJsonTwo(data,name){
        console.log('大小='+new Blob([data]).size)
        const blob = new Blob([qs.hexToArray (data)],{type:"application/octet-binary"})
        const url =URL.createObjectURL(blob)
        const element = document.createElement('a')
        element.style.display = 'none'
        element.href= url

        const indexDot = name.lastIndexOf('.');
        element.download =name.substring(0,indexDot)+new Date().getTime()+name.substring(indexDot,name.length)
        element.click()
    }
   	downLoadJsonThree(data){
        console.log('大小='+new Blob([data.fileContent]).size)
		console.time("下載開始")
        const blob = new Blob([data.fileContent],{type:"application/octet-binary"})
        const url =URL.createObjectURL(blob)
        const element = document.createElement('a')
        element.style.display = 'none'
        element.href= url
        element.download =data.fileName
        element.click()
		console.timeEnd("下載開始")
    }
    decodeToArrayBuffer(str){
        const bstr = atob(str)
        const length = bstr.length
        const unit8Array = new Uint8Array(length)
        for(let i=0;i<length;i++){
            unit8Array[i] = bstr.charCodeAt(i)
        }
        return unit8Array.buffer
    }
  // 获取公钥
   getPublicKeyFun ( data) {
    var prams = {
      opt: 13,
      data: {
        device_id: data,
        /*type:type?1:type*/
      }
    }
       //this.prams = prams
       //this.setInitParams(data)
    this.ws.send (JSON.stringify (prams))
  }

  // 获取签名
  getSignKeyFun ( data) {
    var prams = {
      opt: 14,
      data: {
        device_id:this.deviceObj.device_id,
        encode: 2,
        plain_text: data
      }
    }
      //this.prams = prams
      //this.setInitParams(this.deviceObj.device_id)
    this.ws.send (JSON.stringify (prams))
  }

  // 修改PIN吗
  changePinCode ( data) {
    var prams = {
      opt: 15,
      data: {
        device_id:data.deviceId,
        old_pin: data.oldPin,
        new_pin: data.newPin
      }
    }
      //this.prams = prams
      //this.setInitParams(data.deviceId)
    this.ws.send (JSON.stringify (prams))
  }
}

export default QLibCrypto
